import pkg from '../../../package.json';

import sitePortrait from './sitePortrait';
import parseTaskResult from './parseTaskResult';

function intervalTask({ task, server, runInterval }) {
	let lastRun = Date.now();

	let tid;
	const run = () => {
		let nextTime = runInterval - Date.now() - lastRun;
		nextTime = nextTime < 0 ? runInterval : nextTime;
		tid = setTimeout(() => {
			clearTimeout(tid);
			lastRun = Date.now();
			Promise.resolve(task(server)).finally(run);
		}, nextTime || 10000);
	};

	Promise.resolve(task(server)).finally(run);
}

export default async function systemRepeatTasks(server) {
	const {
		app: {
			config: { [pkg.name]: config },
		},
	} = server;

	if (!process.env.NO_SITE_PORTRAIT) {
		intervalTask({
			server,
			task: sitePortrait,
			runInterval: config.sitePortraitRepeatTask.interval,
		});
	}
	if (!process.env.NO_TASK_PARSE) {
		intervalTask({
			server,
			task: parseTaskResult,
			runInterval: config.parseTaskResultInterval,
		});
	}
}
